﻿
Imports osi.interface.storage
Imports osi.root.formation

Public Class map_sync_accessor
    Inherits base_accessor(Of map_accessor_settings)
    Implements sync_accessor_t

    Private ReadOnly m As map(Of String, bytes) = Nothing

    Public Sub New(ByVal settings As map_accessor_settings)
        MyBase.New(settings)
        m = New map(Of String, bytes)()
    End Sub

    Public Function read(ByVal key As String, ByRef result As bytes) As Boolean Implements sync_accessor_t.read
        Dim it As map(Of String, bytes).iterator = Nothing
        it = m.find(key)
        If it = m.end() Then
            Return False
        Else
            copy(result, (+it).second)
            Return True
        End If
    End Function

    Public Function write(ByVal key As String, ByVal value As bytes) As Boolean Implements sync_accessor_t.write
        If m.size() >= max_key_count() Then
            Return False
        Else
            m(key) = value
            Return True
        End If
    End Function

    Public Function [erase](ByVal key As String) As Boolean Implements sync_accessor_t.erase
        Return m.erase(key)
    End Function

    Public Function exist(ByVal key As String, ByRef result As Boolean) As Boolean Implements sync_accessor_t.exist
        result = m.find(key) <> m.end()
        Return True
    End Function

    Public Function sizeof(ByVal key As String, ByRef result As UInt64) As Boolean Implements sync_accessor_t.sizeof
        Dim it As map(Of String, bytes).iterator = Nothing
        it = m.find(key)
        If it = m.end() OrElse (+it).second Is Nothing Then
            Return False
        Else
            result = (+it).second.size()
            Return True
        End If
    End Function

    Protected Overrides Sub Finalize()
        If settings().debug Then
            raiseError(Convert.ToString(m))
        End If
        GC.KeepAlive(settings())
        GC.KeepAlive(m)
        MyBase.Finalize()
    End Sub
End Class
